<template>
  <section class="pay_content">
    <el-page-header @back="goBack" content="收费"></el-page-header>
    <div class="main_left">
      <div class="pay_left">
        <div class="pay_left_item">
          订单号：
          <br />
          {{orderCode}}
        </div>
        <!-- <div class="pay_left_item">
          门诊号：
          <br />542880000026
        </div>-->
        <div class="pay_left_item pay_left_mb">
          应收金额：
          <br />
          <span class="pay_total">￥{{totalMoney}}</span>
          <!-- <br />{{total | moneyToUpper}} -->
        </div>
        <div class="pay_left_item">
          患者姓名：
          <br />
          {{detail.name}}
        </div>
        <div class="pay_left_item">
          就诊日期：
          <br />
          {{gmtCreate}}
        </div>
        <div v-if="!isSource" class="pay_left_item">
          <span style="cursor: pointer;" @click="getDetail()">查看收费明细 ></span>
        </div>
      </div>
    </div>
    <div class="main_right">
      <div class="main_right_c">
        <el-form ref="form" :model="form" :rules="rules" label-width="140px">
          <el-form-item label="支付类型：">
            <el-checkbox-group
              style="margin-bottom:20px;display:inline-block;"
              v-model="form.source"
              @change="getSource"
            >
              <!-- <el-checkbox :disabled="!qxBtns.gz" :label="2" name="type">挂账金额</el-checkbox>
              <el-checkbox :disabled="!qxBtns.kq" :label="4" name="type">使用卡券</el-checkbox>-->
              <el-checkbox :disabled="!qxBtns.ye" :label="6" name="type">余额支付</el-checkbox>
              <!-- <el-checkbox :disabled="!qxBtns.jf" :label="5" name="type">积分抵扣</el-checkbox> -->
            </el-checkbox-group>
            <el-form-item v-for="(item,index) in sourceItem" style="width:460px;" :key="index">
              <el-input
                :disabled="isChecked"
                @blur="computeMoney"
                type="number"
                v-model="item.payMoney"
              >
                <template slot="prepend">{{item.name}}</template>
                <template slot="append">元</template>
              </el-input>
              <label
                v-if="item.source==6"
                style="text-align:left;color:#9B9B9B;"
              >卡内余额：￥ {{detail.account.amount}}</label>
              <!-- <label v-if="item.source==5" style="text-align:left;color:#9B9B9B;">
                总积分：{{detail.patientScore}} （单次上限{{jfUse.mostNum}}积分）
                温馨提示：积分抵扣会自动计算抵扣金额~
              </label>-->
            </el-form-item>
          </el-form-item>
          <el-form-item label="折扣" prop="discountNumber" style="width:300px;">
            <el-checkbox v-model="isDiscount" @change="computeMoney" name="type"></el-checkbox>
            <el-input
              v-if="isDiscount==true"
              style="width:200px;"
              type="number"
              @blur="computeMoney"
              v-model="form.discountNumber"
            >
              <template slot="append">折</template>
            </el-input>
          </el-form-item>
          <el-form-item label="是否减免：">
            <el-checkbox
              :disabled="!qxBtns.jm"
              v-model="type"
              @change="computeMoney"
              style="width:120px;"
            >是</el-checkbox>
            <div v-if="type==true" style="display:inline-block;width:100%;">
              <el-checkbox-group v-model="form.reductionType">
                <el-checkbox
                  v-for="item in paytypeList"
                  :label="item.id"
                  :key="item.id"
                  style="width:150px"
                  :value="item.id"
                >{{item.desc}}减免</el-checkbox>
              </el-checkbox-group>
            </div>
            <div v-if="type==true">
              <el-input
                style="width:200px;"
                :disabled="showdiscount"
                @blur="computeMoney"
                v-model="form.reductionMoney"
              >
                <template slot="append">元</template>
              </el-input>
              <label style="margin-top:0px;width:initial;">
                （减免折扣
                <el-input v-model="form.discount" disabled class="remission_input"></el-input>%）
              </label>
            </div>
          </el-form-item>
          <el-form-item label>
            <div class="needPay">还需支付：￥{{residueMoney}}</div>
          </el-form-item>
          <!-- 7.现金 8.支付宝 9.微信 10.银行卡 -->
          <el-form-item label="支付方式：" prop="resource" :rules="[residueMoney>0?sourceRules:{}]">
            <el-radio v-model="form.resource" :disabled="!qxBtns.xinjin" label="7">现金</el-radio>
            <!-- <el-radio v-model="form.resource" @change="changeSource" :disabled="!qxBtns.card" label="10">银行卡</el-radio> -->
            <el-radio v-model="form.resource" :disabled="!qxBtns.weixin" label="9">微信</el-radio>
            <el-radio v-model="form.resource" :disabled="!qxBtns.alipay" label="8">支付宝</el-radio>
            <el-radio
              v-model="form.resource"
              style="width:140px;"
              :disabled="!qxBtns.alipay"
              label="18"
            >POS支付</el-radio>
            <el-radio
              v-model="form.resource"
              style="width:140px;"
              :disabled="!qxBtns.alipay"
              label="19"
            >微信小助手</el-radio>
            <!-- <el-radio
              v-model="form.resource"
              style="width:140px;"
              :disabled="!qxBtns.weixin"
              label="16"
            >POS机储蓄卡</el-radio>
            <el-radio
              v-model="form.resource"
              style="width:140px;"
              :disabled="!qxBtns.alipay"
              label="15"
            >POS机信用卡</el-radio>-->
            <el-radio v-model="form.resource" :disabled="!qxBtns.small" label="14">小程序余额支付</el-radio>
            <!-- <el-radio v-model="form.resource" @change="changeSource" :disabled="!qxBtns.small" label="14">POS支付</el-radio> -->
            <!-- <el-radio-group v-model="form.resource">
            </el-radio-group>-->
          </el-form-item>
          <el-form-item label="收费金额：" prop="payMoney">
            <el-input
              v-if="form.resource!=14"
              v-model="form.payMoney"
              disabled
              style="font-size:20px;width:450px;"
              placeholder="请输入收款金额"
            ></el-input>
            <el-form @submit.native.prevent="getSmallCode">
              <el-input
                v-if="form.resource==14"
                :type="textType"
                :disabled="smallDisabled"
                v-model="medicalCard"
                ref="payMoney"
                style="font-size:20px;width:450px;"
                placeholder="请扫描患者电子就诊卡二维码"
              ></el-input>
            </el-form>
          </el-form-item>
          <el-form-item v-if="form.resource==14" label="小程序验证码">
            <el-input
              v-model.number="form.code"
              style="font-size:20px;width:450px;"
              placeholder="请输入小程序付款验证码"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="备注："
            prop="desc"
            :rules="type || isDiscount?[{
            required: true,
            message: '请输入备注',
            trigger: 'blur'
          }]:[]"
          >
            <el-input type="textarea" v-model.trim="form.desc" style="width:450px;"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="btnLoading" @click="onSubmit()">收费</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </section>
</template>
<script>
import validate from "@/_js/validate.js";
import enumArr from "./_js/enum";
export default {
  data() {
    return {
      type: false, //是否减免
      form: {
        payMoney: "",
        xinjin: 0,
        zhifubao: 0,
        resource: "9",
        weixin: 0,
        yinhangka: 0,
        discountNumber: "",
        reductionType: [], //减免类型
        code: "", //小程序code
        medicalCard: "",
        totalMoney: "", //总金额
        note: "", //备注
        recordNum: "", //总积分数量
        realityMoney: "", //实际金额
        orderId: "", //订单id
        discount: "", //折扣数
        reductionMoney: 0, //减免金额
        source: [], //1医保 2挂账 3商保 4.卡券 5.积分 6.余额 7.现金 8.支付宝 9.微信 10.银行卡 11.找零 12.赠送余额  14 小程序余额支付 15 pos机信用卡 16 pos机储蓄卡 18 POS机支付  19 微信小助手
      },
      isDiscount: false, //是否折扣
      btnLoading: false,
      medicalCard: "",
      showdiscount: false,
      sourceItem: [],
      rules: {
        // resource: [
        //   { required: true, message: "请选择支付方式", trigger: "change" }
        // ],
        payMoney: [
          { required: true, message: "请输入收费金额", trigger: "blur" },
          { validator: validate.integerAndFloat, trigger: "blur" },
        ],
        discountNumber: [
          { required: false, message: "请输入正确的折扣", trigger: "blur" },
          { validator: validate.FloatByTwo, trigger: "blur" },
        ],
      },
      checkMoney: {
        validator: validate.integerAndFloat,
        trigger: "blur",
      },
      sourceRules: {
        required: true,
        message: "请选择支付方式",
        trigger: "change",
      },
      isChecked: false,
      total: 0, //用于计算金额（变动）
      totalMoney: 0, //用于显示总金额（不变）
      detail: "",
      orderCode: "",
      show5: false,
      smallDisabled: false,
      qxBtns: {},
      paytypeList: [], //减免方式
      gmtCreate: "",
      textType: "password",
      residueMoney: 0, //剩余支付
      balanceMoney: 0, //找零
      isSource: false,
    };
  },
  created() {
    // this.getIntegralRuleById();
    this.getQX();
    this.getBasicDate();
    // this.getIntegralRuleById();
    this.orderCode = this.$route.query.orderCode;
    this.orderId = this.$route.query.orderId;
    let source = this.$route.query.source;
    if (source) {
      this.isSource = true;
    }
  },
  mounted() {
    this.open();
  },
  methods: {
    getBasicDate() {
      this.getCommonConfigByKey("收费减免类型").then((res) => {
        this.paytypeList = res;
      });
    },
    open() {
      let th = this;
      let total = 0;
      th.verifyUrlAttack(th.$route.query).then(() => {
        if (th.$route.query.patientId) {
          let uid = th.jieMi(th.$route.query.patientId);
          if (uid) {
            var fn = async function () {
              await th.$api
                .getPatientInfo({
                  patientId: uid,
                  hpId: th.adminUser.hpId,
                })
                .then((res) => {
                  if (res.executed) {
                    th.detail = res.dataBody;
                  }
                });
            };
            fn();
          }
        }
        th.$api.getOrder({ orderId: th.$route.query.orderId }).then((res) => {
          if (res.executed) {
            let list = res.dataBody.list;
            if (list) {
              for (let i = 0; i < list.length; i++) {
                total += Number(list[i].realityMoney);
              }
              th.gmtCreate = list[0].gmtCreate;
              th.total = total;
              th.residueMoney = total;
              th.totalMoney = total;
              th.form.payMoney = total;
            }
          }
        });
      });
    },
    getDetail() {
      let th = this;
      let id = "";
      if (th.isSource) {
        id = th.$route.query.orderId;
      } else {
        id = th.$route.query.id;
        th.$router.push({
          path: "/page/chargeDetail",
          query: th.getUrlToken({
            id: id,
            patientId: th.$route.query.patientId,
            isOrder: 1,
          }),
        });
      }
    },
    goBack() {
      let th = this;
      th.$router.push({
        path: "/page/chargeIndex",
        query: th.getUrlToken({
          // total: th.totalMoney,
          type: 0,
        }),
      });
    },
    //循环支付类型金额
    getSource() {
      let list = [];
      let sourceList = this.form.source; //checkbox来源选择项
      let sourceArr = enumArr.sourArr; //来源类型集合
      if (sourceList.length > 0) {
        sourceList.map((it) => {
          let money =
            this.detail.account.amount > this.totalMoney
              ? this.totalMoney
              : this.detail.account.amount;
          list.push({ name: sourceArr[it], payMoney: money, source: it });
        });
      }
      this.sourceItem = list;
      this.computeMoney();
    },
    //计算消费金额
    computeMoney() {
      let total = this.totalMoney; //订单总金额;
      let tMoney = this.totalMoney;
      let patientMoney = this.detail.account.amount; //用户账户余额
      if (Number(this.form.reductionMoney) < 0) {
        this.form.reductionMoney = 0;
      }
      // debugger;
      let discountnum =
        this.form.discountNumber == "" ||
        this.form.discountNumber > 10 ||
        this.form.discountNumber < 0
          ? 10
          : this.form.discountNumber; //折扣数
      discountnum = Number(discountnum / 10);
      let sourcelist = this.sourceItem; //支付方式列表
      let residueMoney = this.residueMoney; //剩余待支付金额
      let reductionMoney = 0;
      if (this.type) {
        reductionMoney = this.form.reductionMoney || 0; //减免金额
      }
      /**方式一、折扣率 */
      if (this.isDiscount) {
        if (Number(total) < 0) {
          this.$message.warning("折扣数有误");
          this.form.discountNumber = "";
          discountnum = 10;
        } else {
          total = Number(total * discountnum).toFixed(2); //计算折扣金额
        }
      }
      /**方式二、减免金额 */
      //当减免金额大于剩余支付金额的情况，将提示用户重新输入金额;
      total -= reductionMoney;
      if (Number(reductionMoney) > Number(residueMoney)) {
        // Number(total) < 0
        this.form.reductionMoney = 0;
        reductionMoney = 0;
        total = Number(tMoney * discountnum - reductionMoney).toFixed(2);
        // this.$message.warning("支付金额大于剩余金额");
      }
      let discount =
        reductionMoney > 0
          ? Number(Number(reductionMoney / tMoney).toFixed(2) * 100).toFixed(2)
          : 0; //计算减免折扣率
      this.form.discount = discount;

      /**方式三、不同支付 */
      //获取不同支付方式支付金额
      if (sourcelist) {
        sourcelist.map((it) => {
          it.payMoney =
            Number(it.payMoney) < 0
              ? Number(patientMoney).toFixed(2)
              : Number(it.payMoney).toFixed(2);
          if (
            Number(it.payMoney) <= patientMoney &&
            Number(total).toFixed(2) >= Number(it.payMoney)
          ) {
            total -= Number(it.payMoney);
          } else if (Number(total).toFixed(2) > Number(it.payMoney)) {
            total -= Number(it.payMoney);
          } else {
            // this.$message.warning("支付金额大于剩余金额");
            it.payMoney = 0;
            // return false;
            this.computeMoney();
          }
        });
      }
      this.residueMoney =
        Number(total).toFixed(2) == 0
          ? Number(0).toFixed(2)
          : Number(total).toFixed(2);
      this.form.payMoney =
        Number(total).toFixed(2) == 0
          ? Number(0).toFixed(2)
          : Number(total).toFixed(2);
    },
    //获取小程序验证码
    getSmallCode() {
      let th = this;
      th.$api
        .createSmallAppCode({ medicalCard: th.medicalCard })
        .then((res) => {
          if (res.executed) {
            th.form.medicalCard = th.medicalCard;
            th.form.payMoney = th.residueMoney;
            th.medicalCard = th.residueMoney;
            th.textType = "text";
            th.smallDisabled = true;
          } else {
            th.$message.error(res.message);
          }
        });
    },
    //获取积分规则
    getIntegralRuleById() {
      this.$api
        .getIntegralRuleById({ hpId: this.adminUser.hpId, type: 1 })
        .then((res) => {
          if (res.executed) {
            this.jfUse = res.integralRuleList[0];
          }
        });
    },
    //提交收费订单
    onSubmit() {
      let _item = [];
      let oldMoney = this.residueMoney; //剩余支付
      let isGz = false; //判断是否挂账
      let reductionType = this.form.reductionType; //获取减免类型
      if (typeof reductionType == "object") {
        this.form.reductionType = reductionType.join(",");
      }
      //卡券积分支付等等
      if (this.sourceItem.length > 0) {
        let list = this.sourceItem;
        list.map((it) => {
          if (it.source === 2) {
            isGz = true;
          }
          _item.push({
            billPayId: "",
            billPayCode: "",
            billId: "",
            payMoney: it.payMoney,
            source: it.source,
            sourceId: "",
            remark: it.note,
            status: "",
            isDeleted: "",
          });
          if (it.source != 6) {
            oldMoney = Number(oldMoney - it.payMoney).toFixed(2);
          }
        });
      }
      //支付方式
      if (this.form.resource == 7) {
        //如果为7是现金支付，需要计算找零金额传给后端；
        _item.push({
          billPayId: "",
          billPayCode: "",
          billId: "",
          payMoney: this.form.payMoney,
          source: 7,
          sourceId: "",
          remark: this.form.desc,
          status: "",
          isDeleted: "",
        });
        // _item.push({
        //   billPayId: "",
        //   billPayCode: "",
        //   billId: "",
        //   payMoney: this.balanceMoney,
        //   source: 11,
        //   sourceId: "",
        //   remark: this.form.desc,
        //   status: "",
        //   isDeleted: ""
        // });
        oldMoney = Number(this.form.payMoney - oldMoney).toFixed(2);
      } else {
        if (this.form.resource != "") {
          _item.push({
            billPayId: "",
            billPayCode: "",
            billId: "",
            payMoney: this.form.payMoney,
            source: this.form.resource,
            sourceId: "",
            remark: this.form.desc,
            status: "",
            isDeleted: "",
          });
          oldMoney = Number(this.form.payMoney - oldMoney).toFixed(2);
        }
      }
      let disnum = "";
      if (this.form.discountNumber) {
        disnum = Number(this.form.discountNumber / 10).toFixed(2);
      }
      let j = {
        orderId: this.orderId, //订单id
        reductionMoney: this.type
          ? this.form.reductionMoney != ""
            ? this.form.reductionMoney
            : 0
          : 0, //减免金额
        note: this.form.desc, //描述
        reductionType: this.form.reductionType, //减免类型
        medicalCard: this.form.medicalCard,
        code: this.form.code, //订单编号
        discountNumber: disnum, //折扣数
        billPaywaysJson: JSON.stringify(_item), //支付方式
      };
      //判断是否挂账
      if (isGz == false) {
        if (Number(oldMoney) < 0) {
          this.$message.error("支付金额不足！");
          this.showLoading(false);
          return false;
        }
      }
      this.btnLoading = true;
      const th = this;
      this.$refs["form"].validate((v) => {
        if (v) {
          th.$confirm(`确定收费吗?`, "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            center: true,
          })
            .then(() => {
              th.showLoading(true);
              th.$api
                .payOrder(j)
                .then((res) => {
                  if (res.executed) {
                    this.$message.success("支付成功");
                    this.$router.push({ path: "/page/chargeIndex" });
                    this.showOrder = true;
                    this.btnLoading = false;
                    this.showLoading(false);
                  } else {
                    this.$message.error(res.message);
                    this.btnLoading = false;
                    this.showLoading(false);
                  }
                })
                .catch((error) => {
                  th.$message.error(res.message);
                  th.btnLoading = false;
                });
            })
            .catch((error) => {
              th.btnLoading = false;
            });
        } else {
          this.btnLoading = false;
        }
      });
    },
    //
  },
  components: {
    pay: () => import("./_child/otherPay"),
  },
};
</script>
<style lang="scss" scoped>
@import "./_css/pay.scss";
.pay_content {
  &::after {
    display: block;
    clear: both;
    visibility: hidden;
    height: 0;
    overflow: hidden;
    content: ".";
  }
  .el-radio {
    width: 120px;
    margin: 0;
    padding: 0;
  }
  .el-form-item {
    margin-bottom: 15px;
  }
  .el-page-header {
    margin-bottom: 20px;
  }
}
.main_left {
  width: 250px;
  float: left;
  position: relative;
  margin-right: -250px;
}
.main_right {
  width: 100%;
  float: right;
  .main_right_c {
    margin-left: 270px;
  }
}
.pay_left {
  padding: 20px;
  background: #40a48b;
  color: #fff;
  .pay_left_item {
    margin-bottom: 30px;
    line-height: 1.5;
  }
  .pay_left_item.pay_left_mb {
    margin-bottom: 80px;
  }
  .pay_total {
    font-size: 30px;
    color: #f9ed54;
  }
}
.el-checkbox-group .el-checkbox {
  width: 120px;
  float: left;
  margin: 0;
  padding: 0;
}
.needPay {
  font-size: 18px;
  font-weight: bold;
  color: #ff5b5b;
}
.danger {
  color: #ff5b5b;
}
.el-form-item__content .el-input-group {
  margin-bottom: 15px;
}
.ml20 {
  margin-left: 20px;
}
</style>